import { createContext, useContext, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { getCookie, setCookie, removeCookie } from '@/lib/cookies'
import { type SupportedLanguage, supportedLanguages } from '@/lib/i18n'

const DEFAULT_LANGUAGE: SupportedLanguage = 'en'
const LANGUAGE_COOKIE_NAME = 'language'
const LANGUAGE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365 // 1 year

type LanguageContextType = {
  defaultLanguage: SupportedLanguage
  language: SupportedLanguage
  setLanguage: (language: SupportedLanguage) => void
  resetLanguage: () => void
  supportedLanguages: typeof supportedLanguages
}

const LanguageContext = createContext<LanguageContextType | null>(null)

export function LanguageProvider({ children }: { children: React.ReactNode }) {
  const { i18n } = useTranslation()
  const [language, _setLanguage] = useState<SupportedLanguage>(() => {
    // Try to get language from cookie first, then from i18n
    const cookieLanguage = getCookie(LANGUAGE_COOKIE_NAME) as SupportedLanguage
    const i18nLanguage = i18n.language as SupportedLanguage
    
    // Validate the language is supported
    const isValidLanguage = (lang: string): lang is SupportedLanguage => 
      supportedLanguages.some(sl => sl.code === lang)
    
    if (cookieLanguage && isValidLanguage(cookieLanguage)) {
      return cookieLanguage
    }
    
    if (i18nLanguage && isValidLanguage(i18nLanguage)) {
      return i18nLanguage
    }
    
    return DEFAULT_LANGUAGE
  })

  useEffect(() => {
    // Sync with i18n when language changes
    if (i18n.language !== language) {
      i18n.changeLanguage(language)
    }
  }, [language, i18n])

  useEffect(() => {
    // Listen to i18n language changes (e.g., from browser detection)
    const handleLanguageChange = (lng: string) => {
      const isValidLanguage = (lang: string): lang is SupportedLanguage => 
        supportedLanguages.some(sl => sl.code === lang)
      
      if (isValidLanguage(lng) && lng !== language) {
        _setLanguage(lng)
        setCookie(LANGUAGE_COOKIE_NAME, lng, LANGUAGE_COOKIE_MAX_AGE)
      }
    }

    i18n.on('languageChanged', handleLanguageChange)
    return () => {
      i18n.off('languageChanged', handleLanguageChange)
    }
  }, [language, i18n])

  const setLanguage = (newLanguage: SupportedLanguage) => {
    _setLanguage(newLanguage)
    setCookie(LANGUAGE_COOKIE_NAME, newLanguage, LANGUAGE_COOKIE_MAX_AGE)
    i18n.changeLanguage(newLanguage)
  }

  const resetLanguage = () => {
    _setLanguage(DEFAULT_LANGUAGE)
    removeCookie(LANGUAGE_COOKIE_NAME)
    i18n.changeLanguage(DEFAULT_LANGUAGE)
  }

  return (
    <LanguageContext.Provider
      value={{
        defaultLanguage: DEFAULT_LANGUAGE,
        language,
        setLanguage,
        resetLanguage,
        supportedLanguages,
      }}
    >
      {children}
    </LanguageContext.Provider>
  )
}

// eslint-disable-next-line react-refresh/only-export-components
export function useLanguage() {
  const context = useContext(LanguageContext)
  if (!context) {
    throw new Error('useLanguage must be used within a LanguageProvider')
  }
  return context
}
